package com.gome.ocean.controller.authority;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.github.pagehelper.Page;
import com.gome.ocean.common.constants.Constants;
import com.gome.ocean.common.utils.ResponsePage;
import com.gome.ocean.dao.model.authority.Function;
import com.gome.ocean.dao.model.authority.Role;
import com.gome.ocean.dao.model.authority.RoleFunction;
import com.gome.ocean.service.authority.FunctionService;
import com.gome.ocean.service.authority.RoleFunctionService;
import com.gome.ocean.service.authority.RoleService;
import com.gome.ocean.service.base.BaseController;

/**
 * Created by liuqingxia on 2016/6/20.
 */
@Controller
@RequestMapping("/role")
public class RoleController extends BaseController {

    private static final Logger LOG = LoggerFactory.getLogger(RoleController.class);

    @Autowired
    private RoleService         roleService;
    @Autowired
    private RoleFunctionService roleFunctionService;
    @Autowired
    private FunctionService     functionService;

    @RequestMapping(value = "/toInsertPage", method = RequestMethod.GET)
    public String toInsertPage(ModelMap map) {
        Map<String, List<Function>> funGroupByModule = functionService.findFunctionGroupByModule();
        map.put("funGroupByModule", funGroupByModule);
        return "authority/role/insert";
    }

	@SuppressWarnings("rawtypes")
	@RequestMapping(value = "/insert", method = RequestMethod.POST)
    @ResponseBody
    public ResponsePage insert(String functionIds,String roleName,String desc) {
        ResponsePage response = getResponsePage();
        Role roleIsHad = roleService.getRoleByRoleName(roleName.trim());
        if (roleIsHad != null) {
        	return response.setErrorMsg("角色名称已经存在,请重新输入");
		}
        Role role = extractRoleFormReq(roleName,desc);
        List<Long> funcIds = transFuncIdList(functionIds);
        if (funcIds.isEmpty()) {
    		return response.setErrorMsg("您没有选择该角色的任何功能权限，请重新选择");
		}
        try {
            roleService.insertRole(role);
            roleFunctionService.insertRoleFunction(role.getId(), funcIds);
            return response.setSuccessMsg("新建角色及其相关的权限表成功");
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            return response.setErrorMsg("新建角色过程中发生异常");
        }
    }

    private List<Long> transFuncIdList(String functionIds) {
    	List<Long> list  = new ArrayList<Long>();
    	if (functionIds != null) {
    		String[] str = functionIds.split(",");
    		for(String s : str){
    			list.add(Long.parseLong(s));
    		}
		}
    	
        return list;
    }

    private Role extractRoleFormReq(String roleName,String desc) {
    	Role role = new Role();
    	role.setName(roleName);
    	role.setDescriptor(desc);
        return role;
    }

    @RequestMapping(value = "/remove", method = RequestMethod.POST)
    @ResponseBody
    public ResponsePage remove(@RequestParam("id")Long id) {
    	ResponsePage rep = getResponsePage();
    	try {
			if (roleService.removeRole(id)) {
				return rep.setSuccessMsg("删除成功");
			}
			return rep.setErrorMsg("删除失败");
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
            return rep.setErrorMsg(e.getMessage());
		}
    }
    
    @RequestMapping(value = "/toUpdatePage" ,method = RequestMethod.GET)
    public ModelAndView toUpdatePage(ModelAndView mav,String currentId){
    	Long roleId = Long.parseLong(currentId);
    	Role role = roleService.findRoleById(roleId);
    	List<RoleFunction> roleFunctionList = roleFunctionService.findRoleFunctionByRoleId(roleId);
    	Map<String, List<Function>> funGroupByModule = functionService.findFunctionGroupByModule();
    	Iterator<Entry<String, List<Function>>> it = funGroupByModule.entrySet().iterator();
    	while(it.hasNext()){
    		List<Function> funcList = it.next().getValue();
    		for (RoleFunction roleFunc : roleFunctionList) {
				for (Function function : funcList) {
					if (roleFunc.getFuncid().equals(function.getId())) {
						function.setCheckedType(1);
					}
				}
			}
    	}
        mav.addObject("funGroupByModule", funGroupByModule);
    	mav.addObject("role", role);
    	mav.setViewName("authority/role/role-update");
    	return mav;
    }
    
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    @ResponseBody
    public ResponsePage update(String roleId,String functionIds,String roleName,String desc) {
    	ResponsePage response = getResponsePage();
    	Long id = Long.parseLong(roleId);
        Role roleIs = roleService.getRoleByRoleName(roleName);
        Role role2 = roleService.findRoleById(id);
        if (roleIs!=null && !roleName.equals(role2.getName())) {
        	return response.setErrorMsg("角色已经存在，请重新填写");
		}
        List<Long> funcIds = transFuncIdList(functionIds);
        if (funcIds.isEmpty()) {
    		return response.setErrorMsg("您没有选择该角色的任何功能权限，请重新选择");
		}
        try {
        	boolean flag = roleFunctionService.deleteRoleFuncByRoleId(id);
        	if (flag) {
        		roleFunctionService.insertRoleFunction(id, funcIds);
        		return response.setSuccessMsg("修改角色及其相关的权限表成功");
			}
            
            return response.setErrorMsg("删除过程中发生失败，请联系管理员");
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            return response.setErrorMsg("新建角色过程中发生异常");
        }
    }
    
    /**
     * 查询角色
     * */
    @RequestMapping(value = "/find",method = RequestMethod.GET)
    public ModelAndView findRolePage(ModelAndView mav){
    	mav.setViewName("authority/role/find");
    	return mav;
    }
    @RequestMapping(value = "/find", method = RequestMethod.POST)
    @ResponseBody
    public ResponsePage find(HttpServletRequest req) {
    	String name = req.getParameter("name");
    	String pageNumStr = req.getParameter("pageNum");
    	int pageNum = Constants.DEFAULT_PAGE_NUM;
    	if (!StringUtils.isBlank(pageNumStr)) {
			pageNum = Integer.parseInt(pageNumStr.trim());
		}
    	String pageSizeStr = req.getParameter("pageSize");
    	int pageSize = Constants.DEFAULT_PAGE_SIZE;
    	if (!StringUtils.isBlank(pageSizeStr)) {
			pageSize = Integer.parseInt(pageSizeStr.trim());
		}
    	ResponsePage page = new ResponsePage();
    	try {
			Page<Role> rolePage = null;
			Role role = null;
			if (StringUtils.isBlank(name)) {
				rolePage = roleService.findAllRoles(pageNum, pageSize);
				return page.setPage(rolePage, "查询成功");
			}else{
				Role role2 = roleService.getRoleByRoleName(name);
				rolePage = new Page<Role>();
				rolePage.add(role2);
				rolePage.setTotal(1);
				if (role2 != null) {
					return page.setPage(rolePage, "查询成功");
				}
				return page.setSuccessMsg("暂无数据");
			}
		} catch (Exception e) {
			LOG.error(e.toString());
			return page.setErrorMsg("异常信息:" + e.toString());
		}
    	
    }
    
    /**
     * 校验角色名称是否重复
     * */
    @RequestMapping(value = "/findRoleName", method = RequestMethod.POST)
    @ResponseBody
    public ResponsePage findRoleName(String roleName){
    	ResponsePage res = getResponsePage();
    	Role role = roleService.getRoleByRoleName(roleName);
    	if (role != null) {
			return res.setErrorMsg("角色名称已经存在,请重新输入!");
		}
    	return res.setSuccessMsg("success");
    }
}
